package com.meixiang.activity.account.myShopper;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.personalCenter.OrderEvaluationAdapter;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.dialog.SelectDialog;
import com.meixiang.entity.myOrder.EvaluateCommit;
import com.meixiang.entity.myOrder.EvaluateSuccessData;
import com.meixiang.entity.myOrder.MyOrderDetail;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbFileUtils;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.photoSelectActivity.util.Bimp;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author yinsujun  Created at 2016/5/9 19:27
 *         订单已收货评价
 */
public class OrderEvaluationActivity extends BaseActivity implements OrderEvaluationAdapter.OnPhotoSelect{
    @Bind(R.id.order_evaluation_recycler_view)
    RecyclerView mRecyclerView;
    @Bind(R.id.order_evaluation_bt_commit)
    Button btCommit;
    @Bind(R.id.order_evaluation_bottom)
    LinearLayout orderEvaluationBottom;
    private OrderEvaluationAdapter evaluationAdapter;
    private String orderId;
    private MyOrderDetail orderDetail;
    private DeleteSelectPhotoBroad broadCast;

    /**
     * 评论提交成功返回集合
     */
    private List<EvaluateSuccessData> evaluateSuccessDataList;

    private int photoSelect=-1;
    private static final int CAMERA_CODE = 0x00; // 拍照的权限


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_evaluation);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        registerBroadCast();



    }

    private void registerBroadCast(){
        broadCast=new DeleteSelectPhotoBroad();
        IntentFilter intentFilter=new IntentFilter(GlobalType.EVALUATE_ORDER_DELETE_PHOTO);
        registerReceiver(broadCast, intentFilter);
    }
    @Override
    protected void initTitle() {
        setTitle("待评价", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialogFragment.Builder()
                        .setContentText("亲，评价还未完成，您确定要离开？")
                        .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                    @Override
                    public void dialogLeftBtnClick() {
                        Bimp.tempSelectBitmap.clear();
                        OrderEvaluationActivity.this.finish();
                    }
                }).setRightBtnText("取消")
                        .build()
                        .show(getSupportFragmentManager(), AlertDialogFragment.TAG);

            }
        });
    }

    @Override
    protected void initView() {
        orderId=getIntent().getStringExtra("orderId");
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        if(Bimp.tempSelectBitmap.size()>0){
            Bimp.tempSelectBitmap.clear();
        }
    }

    @Override
    protected void setData() {
        evaluationAdapter=new OrderEvaluationAdapter(this);
        evaluationAdapter.setOnPhotoSelect(this);
        getOrderEvaluateData();
        mRecyclerView.setAdapter(evaluationAdapter);
    }

    private void getOrderEvaluateData(){
        String url= Config.ORDER_FOR_EVALUATE;
        HttpParams params=new HttpParams();
        params.put("orderId", orderId);
        status.showLoading();
        HttpUtils.post(url, params, new HttpCallBack(OrderEvaluationActivity.this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                status.removeView();
                MyOrderDetail orderDetails = AbJsonUtil.fromJson(result.toString(), MyOrderDetail.class);
                orderDetail = orderDetails;
                for(int i=0;i<orderDetails.getOrderGoodsList().size();i++){
                    if(orderDetails.getTagList()!=null&&orderDetails.getTagList().size()>0){
                        //orderDetails.getTagList()
                        List<MyOrderDetail.TagListBean> tagList =new ArrayList<>() ;
                        for(int j=0;j<orderDetails.getTagList().size();j++){
                            MyOrderDetail.TagListBean tagListBean=new MyOrderDetail.TagListBean();
                            tagListBean.setSelect(false);
                            tagListBean.setTagId(orderDetails.getTagList().get(j).getTagId());
                            tagListBean.setTagName(orderDetails.getTagList().get(j).getTagName());
                            tagList.add(tagListBean);
                        }
                        orderDetails.getOrderGoodsList().get(i).setTagId(tagList);
                    }
                }
//                orderDetails.getOrderGoodsList().get(0).getTagId().get(0).setSelect(true);
//                for(int i=0;i<orderDetails.getOrderGoodsList().size();i++){
//                    orderDetails.getOrderGoodsList().get(0).getTagId().get(0).setSelect(true);
//                    Log.e(TAG,i+"==状态=="+orderDetails.getOrderGoodsList().get(i).getTagId().toString());
//                }
                evaluationAdapter.addOrder(orderDetails);

            }

            @Override
            public void onError(String code, String message) {
                status.removeView();
                Tool.showTextToast(context, message);

            }
        });



    }

    private void submitEvaluate(){
        String url=Config.ORDER_FOR_EVALUATE_SUMBIT;
        HttpParams params=new HttpParams();

        EvaluateCommit gevalParameter = evaluationAdapter.getGevalParameter();
//        List<EvaluatePhoto> evaluatePhotos = evaluationAdapter.getEvaluatePhotos();
        final List<MyOrderDetail.OrderGoodsListBean> orderGoodsList = evaluationAdapter.getOrderDetail().getOrderGoodsList();

//        if(orderGoodsList!=null&&orderGoodsList.size()>0){
//            for(int i=0;i<orderGoodsList.size();i++){
//                if(orderGoodsList.get(i).getPhoto()!=null&&orderGoodsList.get(i).getPhoto().size()>0){
//                    Log.e(TAG,orderGoodsList.get(i).getPhoto().toString()+"========"+orderGoodsList.get(i).getPhoto().size()+"===文件数据=="+i);
//                    for(int k=0;k<orderGoodsList.get(i).getPhoto().size();k++){
//                        String file1=orderGoodsList.get(i).getPhoto().get(k);
//                        Log.e(TAG,"文件大小==="+AbFileUtils.getFileSizeFor(new File(file1)));
//                        try {
//                            Bitmap bitmap = Bimp.revitionImageSize(file1);
//                            if(bitmap==null){
//                                Log.e(TAG,"图片转bitmap失败");
//                                return;
//                            }else{
//                                Log.e(TAG,"图片转bitmap成功");
//                                Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
//                                //创建新的照片
//                                File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
//                                String imgName = mFolder.getAbsolutePath()+"mx" + System.currentTimeMillis() + ".png";
//                                File file = AbFileUtils.saveFile(bitmap1, imgName);
//                                Log.e(TAG,"上传文件大小==="+AbFileUtils.getFileSizeFor(file));
//                            }
//
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
////                        Bitmap bitmap=BitmapFactory.decodeFile(file1
////                                ,AbFileUtils.getBitmapOptions(file1));
////                        if(bitmap==null){
////                            Log.e(TAG,"图片转bitmap失败");
////                            return;
////                        }
////                        Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
////                        //创建新的照片
////                        String imgName = "mx_s" + System.currentTimeMillis() + ".png";
////                        File file = AbFileUtils.saveFile(bitmap1, imgName);
////                        Log.e(TAG,"上传文件大小==="+AbFileUtils.getFileSizeFor(file));
//
//                    }
//
//                }
//            }
//        }

        if(orderGoodsList!=null&&orderGoodsList.size()>0){
            for(int i=0;i<orderGoodsList.size();i++){
                if(orderGoodsList.get(i).getTagId()!=null&&orderGoodsList.get(i).getTagId().size()>0){
//                List<String> tagList = orderGoodsList.get(i).getTagId();
                    List<String> tagList=new ArrayList<>();
                    List<MyOrderDetail.TagListBean> tagId = orderGoodsList.get(i).getTagId();
                    if(tagId!=null&&tagId.size()>0){
                        for(int j=0;j<tagId.size();j++){
                            if(tagId.get(j).isSelect()==true){
                                tagList.add(tagId.get(j).getTagId());
                            }
                        }
                        evaluationAdapter.getGevalParameter().getGevalGoodsList().get(i).setTagIdArray(tagList);
                    }
                    Log.e(TAG,"选中标签===="+tagList.toString());
                }
            }
        }

        Log.e(TAG,"json数据=="+AbJsonUtil.toJson(gevalParameter));
        if(orderDetail!=null&&gevalParameter!=null) {
            if (gevalParameter != null && gevalParameter.getGevalGoodsList().size() > 0) {
                for (int i = 0; i < gevalParameter.getGevalGoodsList().size(); i++) {
                    if (AbStrUtil.isEmpty(gevalParameter.getGevalGoodsList().get(i).getScores())
                            ||Integer.parseInt(gevalParameter.getGevalGoodsList().get(i).getScores()) == 0) {
                        Tool.showTextToast(context, "请选择评分");
                        return;
                    }
                    if (AbStrUtil.isEmpty(gevalParameter.getGevalGoodsList().get(i).getGevalContent())) {
                        gevalParameter.getGevalGoodsList().get(i).setGevalContent(gevalParameter.getGevalGoodsList().get(i).getScoresText());
                    }
                }
            }
        }
        Log.e(TAG,"json数据222222=="+AbJsonUtil.toJson(gevalParameter));
        params.put("gevalParameter",AbJsonUtil.toJson(gevalParameter));

//        for(int i=0;i<orderGoodsList.size();i++){
//            List<String> imagePath=orderGoodsList.get(i).getPhoto();
//
//            if(imagePath!=null&&imagePath.size()>0){
//                List<File> fileList=new ArrayList<File>();
//                for(int j=0;j<imagePath.size();j++){
////                            File file = new File(imagePath.get(j));
//                    File file = getCompressFile(imagePath.get(j));
//                    Log.e(TAG,"上传文件大小==="+AbFileUtils.getFileSizeFor(file));
//                    if(file!=null){
//                        fileList.add(file);
//                    }
//                }
//                Log.e(TAG,"上传图片==="+fileList.size());
////                if(fileList.size()>0){
////                    uploadImage(evaluateSuccessDataList.get(i).getGevalId(),fileList);
////                }
//            }
//        }

        HttpUtils.post(url,params,new HttpCallBack(this,"正在提交评价"){
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if(!AbStrUtil.isEmpty(result.toString())&&result.toString().contains("gevalList")){
                    evaluateSuccessDataList=AbJsonUtil.fromJson(result.optJSONArray("gevalList").toString(),new TypeToken<ArrayList<EvaluateSuccessData>>(){});
                    for(int i=0;i<evaluateSuccessDataList.size();i++){
                        List<String> imagePath=orderGoodsList.get(i).getPhoto();

                        if(imagePath!=null&&imagePath.size()>0){
                            List<File> fileList=new ArrayList<File>();
                            for(int j=0;j<imagePath.size();j++){
//                            File file = new File(imagePath.get(j));
                                File file = getCompressFile(imagePath.get(j));
                                Log.e(TAG,"上传文件大小==="+AbFileUtils.getFileSizeFor(file));
                                if(file!=null){
                                    fileList.add(file);
                                }
                            }
                            Log.e(TAG,"上传图片==="+fileList.size());
                            if(fileList.size()>0){
                                uploadImage(evaluateSuccessDataList.get(i).getGevalId(),fileList);
                            }
                        }

                    }

                    Intent intent=new Intent(GlobalType.ORDER_DETAIL_OPERATION);
                    sendBroadcast(intent);

                    OrderEvaluationActivity.this.finish();
                }
                Tool.showTextToast(context,message);
            }
            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });

    }
    /**
     * 压缩图片上传
     * @param file1
     * @return
     */
    private File getCompressFile(String file1){
        Log.e(TAG,"文件大小==="+AbFileUtils.getFileSizeFor(new File(file1)));
        Log.e(TAG,"文件路径==="+file1);
        try {
            Bitmap bitmap = Bimp.revitionImageSize(file1);
            if(bitmap==null){
                Log.e(TAG,"图片转bitmap失败");
                return null;
            }else{
                Log.e(TAG,"图片转bitmap成功");
                Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
                //创建新的照片
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
                    if (!mFolder.exists()) {
                        mFolder.mkdirs();
                    }
                    String filePath=file1;
                    if(filePath.contains(".")){
                        filePath=filePath.substring(filePath.lastIndexOf("/")+1,filePath.indexOf("."));
                    }
                    String imgName = mFolder.getAbsolutePath() + filePath+ ".jpg";
                    File compressPath=new File(imgName);
                    if(compressPath.exists()){
                        Log.e(TAG,"压缩文件路径存在=="+compressPath.getAbsolutePath());
                        return compressPath;
                    }else{
                        File file = AbFileUtils.saveFile(bitmap1, imgName);
                        Log.e(TAG,"压缩文件路径=="+file.getAbsolutePath());
                        return file;
                    }
                }else{
                    AbToastUtil.showToast(context, context.getResources().getString(R.string.account_manage_no_sd_card));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传图片
     */
    private void uploadImage(String gevalId,List<File> files){
        String url=Config.ORDER_FOR_EVALUATE_UPLOAD_PICTURE;
        HttpParams params=new HttpParams();
        params.put("gevalId",gevalId);
        HttpUtils.postFiles(url, params, "imageFile", files, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);

            }
        });
    }


    @OnClick(R.id.order_evaluation_bt_commit)
    void click(View v){
        if(v.equals(btCommit)){
            submitEvaluate();
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPhotoClickSelect(View view, int position) {
        photoSelect=position;
        if(evaluationAdapter.getOrderDetail().getOrderGoodsList().get(position).getPhoto()!=null
                &&evaluationAdapter.getOrderDetail().getOrderGoodsList().get(position).getPhoto().size()>0){
            if(evaluationAdapter.getOrderDetail().getOrderGoodsList().get(position).getPhoto().size()>=GlobalType.ORDER_PICTURE_COUNT){
                Tool.showTextToast(context,"最多只能选择"+GlobalType.ORDER_PICTURE_COUNT+"张");
                return;
            }
        }
        new SelectDialog(context, new String[]{"拍照上传", "相册选择"}, new SelectDialog.IResultListener() {
            @Override
            public void SelectResult(int result) {
                if (result == 0) {
                    //拍照
                    if (Build.VERSION.SDK_INT >= 23) {
                        MPermissions.requestPermissions(OrderEvaluationActivity.this, CAMERA_CODE,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE});
                    }else{
                        photoGraph();
                    }
                } else {
                    //手机相册
                    localImage();
                }
            }
        });
    }

    /**
     * 图片文件选择
     */

    private void localImage() {
        Intent intent = new Intent(context,PhotoFileEvaluateActivity.class);
        intent.putExtra("photoType", GlobalType.EVALUATE_ORDER_SELECT_PHOTO);
        if(evaluationAdapter.getOrderDetail().getOrderGoodsList().get(photoSelect).getPhoto()!=null
                &&evaluationAdapter.getOrderDetail().getOrderGoodsList().get(photoSelect).getPhoto().size()>0){
            intent.putExtra("selectImageSize",evaluationAdapter.getOrderDetail().getOrderGoodsList().get(photoSelect).getPhoto().size());
        }
        startActivityForResult(intent,100);

    }

    /**
     * 拍照
     */
    private File imgFile;//相机拍照存放地址

    private void photoGraph() {
        //判断内存卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //创建文件夹
            File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
            //判断是否存在，不存在则创建
            if (!mFolder.exists()) {
                mFolder.mkdirs();
            }
//            //删除存在的照片
//            File files[] = mFolder.listFiles(); // 声明目录下所有的文件 files[];
//            for (int i = files.length - 1; i >= 0; i--) { // 遍历目录下所有的文件
//                files[i].delete();// 删除
//            }
            //创建新的照片
            String imgName = "mx_" + System.currentTimeMillis() + ".png";
            imgFile = new File(mFolder, imgName);
            //打开相机
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            captureIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            //保存路径
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            Log.e("TAG","输出照相路径==="+Uri.fromFile(imgFile));
            startActivityForResult(captureIntent, 101);
        } else {
            AbToastUtil.showToast(context, context.getResources().getString(R.string.account_manage_no_sd_card));
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ArrayList<String> tempList = new ArrayList<String>();
        if(requestCode==100&&resultCode==200){
            //相册选择
            ArrayList<String> fileName = data.getStringArrayListExtra("fileName");
            tempList.addAll(fileName);
            evaluationAdapter.addPhotoItem(photoSelect,tempList);
        }else if(requestCode==101&&resultCode==RESULT_OK){
            //拍照
//                String fileName = imgFile.getAbsolutePath();
//                 Bitmap assetsBitmap = Tool.getAssetsBitmap(context, fileName);
//                ImageItem takePhoto = new ImageItem();
//                takePhoto.setBitmap(assetsBitmap);
//                takePhoto.setImagePath(fileName);
//                allUploadFile.add(imgFile);
//                Bimp.tempSelectBitmap.add(takePhoto);
//                evaluationAdapter.addSelectImage(Bimp.tempSelectBitmap);
            if(!AbStrUtil.isEmpty( imgFile.getAbsolutePath())){
                String path = imgFile.getAbsolutePath();
                tempList.add(path);
                evaluationAdapter.addPhotoItem(photoSelect, tempList);
            }else{
//                Tool.showTextToast(context,"拍照失败");
                Log.e(TAG,"=========未保存照片");
            }


        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            new AlertDialogFragment.Builder()
                    .setContentText("亲，评价还未完成，您确定要离开？")
                    .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                @Override
                public void dialogLeftBtnClick() {
                    Bimp.tempSelectBitmap.clear();
                    OrderEvaluationActivity.this.finish();
                }
            }).setRightBtnText("取消")
                    .build()
                    .show(getSupportFragmentManager(), AlertDialogFragment.TAG);

        }
        return true;
    }

    private class DeleteSelectPhotoBroad extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            int position=intent.getIntExtra("position",0);
            int orderPosition=intent.getIntExtra("orderPosition",0);
            evaluationAdapter.getOrderDetail().getOrderGoodsList().get(orderPosition).getPhoto().remove(position);
            evaluationAdapter.notifyDataSetChanged();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @PermissionGrant(CAMERA_CODE)
    public void requestSdcardSuccess() {
        photoGraph();
    }

    @PermissionDenied(CAMERA_CODE)
    public void requestSdcardFailed() {
        Toast.makeText(activity, "无法启动系统照相机!", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadCast);
    }
}
